// Cursor API服务

// 配置
const API_BASE_URL = 'https://api.cursor.com';
// 删除硬编码的API密钥

// 可能的端点
const ENDPOINTS = {
  ANALYZE_BOOKMARKS: '/analyze',
  CATEGORIZE: '/categorize',
};

// 获取保存的API密钥
const getApiKey = async (): Promise<string> => {
  try {
    const result = await chrome.storage.local.get('cursorApiKey');
    return result.cursorApiKey || '';
  } catch (error) {
    console.error('获取API密钥失败:', error);
    return '';
  }
};

// 调用Cursor API进行书签分析
export const analyzeBookmarks = async (bookmarks: any[]) => {
  try {
    const apiKey = await getApiKey();
    
    if (!apiKey) {
      throw new Error('未设置API密钥');
    }
    
    const response = await fetch(`${API_BASE_URL}${ENDPOINTS.ANALYZE_BOOKMARKS}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiKey}`
      },
      body: JSON.stringify({ bookmarks })
    });

    if (!response.ok) {
      throw new Error(`API请求失败: ${response.status} ${response.statusText}`);
    }

    return await response.json();
  } catch (error) {
    console.error('调用Cursor API时出错:', error);
    throw error;
  }
};

// 使用Cursor API对书签进行分类
export const categorizeBookmarks = async (bookmarks: any[]) => {
  try {
    const apiKey = await getApiKey();
    
    if (!apiKey) {
      throw new Error('未设置API密钥');
    }
    
    const response = await fetch(`${API_BASE_URL}${ENDPOINTS.CATEGORIZE}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiKey}`
      },
      body: JSON.stringify({ bookmarks })
    });

    if (!response.ok) {
      throw new Error(`API请求失败: ${response.status} ${response.statusText}`);
    }

    return await response.json();
  } catch (error) {
    console.error('调用Cursor API分类时出错:', error);
    throw error;
  }
};

// 如果需要，你可以添加更多API调用方法 